/*
* ============================================================================
* 功能描述 ：温湿度
* 作者       ：ggls
* 创建日期 ：2024.04.24
* ----------------------------------------------------------------------------
* 更新历史 ：
*	日期 　　- 修改者   : 更新内容描述
*
* ============================================================================
*/

#include "main.h"

/* SHT4X写一个字节 */
unsigned char SHT4XWriteByte(unsigned char Address,unsigned char dat)
{
    I2CStart();
   tmp_write_byte(Address);
   read_ACK();
   tmp_write_byte(dat);
   read_ACK();
    I2CStop();

    return 1;
}
/* SHT4X读多字节  */
unsigned char SHT4XReadSerial(unsigned char Address,unsigned char *dat,unsigned char len)
{
    unsigned char ACK;

    I2CStart();
     tmp_write_byte(Address);
   read_ACK();
    while(len > 1)
    {
        *dat++ = I2CReadACK();
        len--;
    }
    *dat = I2CReadNAK();//最后一个字节为读取操作+非应答
    I2CStop();

    return 1;
}
/* 读取温湿度 */
unsigned char SHT4XReadTemperatureAndHumidity(s16 *temperature,s16 *humidity)
{
    unsigned char RxBuff[6];
    s16 HdataBuf, TdataBuf;
    float Hdata,Tdata;
	char ch[6];
    I2CInit();
	_nop_();

    RxBuff[0] = SHT4XWriteByte(0x88,0xfd);
    if(RxBuff[0] == 0)
    {
        //SCL SDA 设置上拉输入
		SDA_in;
		SCL_in;

		GPIO_ENABLE_UP(P1UP, GPIO_PIN_5);				//开启上拉
		GPIO_ENABLE_UP(P1UP, GPIO_PIN_6);				//开启上拉
        return 0;//没收到SHT4X的ACK
    }
    delayms(10);//延时等待测量
    SHT4XReadSerial(0x89,RxBuff,6);

    //SCL SDA 设置上拉输入
   		SDA_in;
		SCL_in;

		GPIO_ENABLE_UP(P1UP, GPIO_PIN_5);				//开启上拉
		GPIO_ENABLE_UP(P1UP, GPIO_PIN_6);				//开启上拉
	
     Tdata = RxBuff[0]*256 + RxBuff[1];
    Hdata = RxBuff[3]*256 + RxBuff[4];
  	TdataBuf = (s16)(175.0f * (Tdata * 100.0f / 65535.0f) - 4500.0f);
	HdataBuf = (s16)(125.0f * (Hdata * 100.0f / 65535.0f) - 600.0f);


    //*temperature = (signed short)Tdata;
    *temperature = TdataBuf;
    *humidity = HdataBuf;

    return 1;
}



